<template>
  <!-- 承办领导/部门负责人 -->
  <!-- 功能：懒加载、懒加载状态、可搜索 -->
  <a-select
    v-model="currentValue"
    v-bind="$attrs"
    :label-in-value="labelInValue"
    show-search
    style="width: 100%"
    :filter-option="false"
    v-on="$listeners"
    @popupScroll="(name, e) => handleScroll(name, e)"
    @search="handleSearch"
    @change="handleChange"
  >
    <a-icon
      v-if="fetching"
      slot="suffixIcon"
      style="color: #096dd9"
      type="loading"
    />
    <a-select-opt-group
      v-for="(i, index) in data"
      v-show="i && i.userId"
      :key="index"
    >
      <span slot="label"> <a-icon type="user" />{{ i.name }} </span>
      <a-select-option
        v-for="j in i.postParentList"
        v-show="j && j[0].id"
        :key="i.userId + '/' + j[0].id"
        :value="i.userId + '/' + j[0].id"
      >
        {{ i.name + ': ' + j[0].name }}
      </a-select-option>
    </a-select-opt-group>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { getEmployees } from '@/api/businessAffairs/revenueAndCost'

export default {
    props: {
        value: {
            type: [Object, String, Array, Number]
        },
        labelInValue: {
            type: Boolean,
            default: () => true
        },
        orgId: {
            type: String,
            default: () => undefined
        },
        isDefault: {
            type: Boolean,
            default: () => true
        },
        //默认查询下级下下级所有人员,true只查下一级人员
        isInclude: {
            type: Boolean,
            default: () => false
        },
       init: {
            type: Boolean,
            default: () => true
        },
        // 请求参数
        requestParams: {
            type: Object,
            default: () => {
                return {}
            }
        }
    },
    watch: {
        orgId: {
            deep: true,
            handler: function (val) {
              // 这里是之前的前端没考虑顺序导致的 所以注释了
              // this.currentValue = undefined
              // this.$emit('input', undefined)
              this.baseData = this.data = []
              if (val) {
                    this.handleEmployees()
                }
            }
        }
    },
    data() {
        this.lastFetchId = 0
        this.handleSearch = debounce(this.handleSearch, 800)
        return {
            data: [],
            baseData: [],
            fetching: false,
            noScroll: true,
            pageNumber: 1,
            totalPages: 1,
            searchVal: '',
            rootOrgId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id
        }
    },
    computed: {
        currentValue: {
            get: function () {
                return this.value
            },
            set: function (e) {
                if (e && this.data?.length > 0) {
                    e.keyId = e.key
                    this.$emit('input', e)
                    this.$emit(
                        'getOption',
                        this.data.find((item) => item.userId === e)
                    )
                    // 单选返回选中项
                    if (!Array.isArray(e)) {
                        this.$emit(
                            'getItem',
                            this.data.find((item) => item.userId === e.key.split('/')[0])
                        )
                    }
                }
            }
        }
    },
    mounted() {
        /**
         * 督办部门负责人
         * */

       this.init && this.handleEmployees()
    },
    methods: {
        /**
         * 模糊搜索
         */
        handleSearch(value) {
            this.lastFetchId += 1
            this.data = []
            this.fetching = true
            this.searchVal = value
            this.handleEmployees(value, 1)
        },
        handleChange() {
            Object.assign(this, {
                data: this.baseData,
                fetching: false
            })
        },
        /**
         * 下拉滚动加载
         */
        handleScroll(e) {
            let that = this
            const { target } = e
            var total = target.scrollTop + target.offsetHeight
            var scrollHeight = target.scrollHeight
            // this.pageNo是当前页 this.totalPage是总页数
            if (
                total >= scrollHeight - 1 &&
                total < scrollHeight + 1 &&
                that.pageNumber <= that.totalPages &&
                that.noScroll
            ) {
                that.pageNumber += 1
                that.handleEmployees()
            }
            if (that.pageNumber > that.totalPages) {
                that.noScroll = false
                that.pageNumber = 1
            } else {
                that.noScroll = true
            }
        },

        /**
         * 承办领导/部门负责人
         */
        handleEmployees(val, searchPageNumber) {
            this.fetching = true
            const pageNumber = searchPageNumber ? searchPageNumber : this.pageNumber
            let params = {
                pageNumber: pageNumber,
                pageSize: 10,
                queryPostRelation: true,
                rootOrgId: this.isInclude ? void 0 : this.isDefault ? this.rootOrgId : this.orgId,
                orgId: this.isInclude ? (this.isDefault ? this.rootOrgId : this.orgId) : void 0,
                nameLike: this.searchVal
            }
            // 添加额外参数
            if (Object.keys(this.requestParams)?.length > 0) {
                params = Object.assign({}, params, this.requestParams)
            }
            getEmployees(params)
                .then((res) => {
                    if (!val) {
                        this.data = this.data.concat(res.data.list)
                        this.baseData = this.data
                    } else {
                        const fetchId = this.lastFetchId
                        if (fetchId !== this.lastFetchId) {
                            // for fetch callback order
                            return
                        }
                        this.data = res.data.list
                    }
                    this.totalPages = res.data.total
                    this.fetching = false
                })
                .catch(() => {
                    this.fetching = false
                })
        }
    }
}
</script>
